<?php
declare (strict_types = 1);

namespace app\command;

use app\core\Wechat;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;

class Hello extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('hello')
            ->setDescription('the hello command');
    }

    protected function execute(Input $input, Output $output)
    {
        $wechat = new Wechat();
        $user_ids = Db::name("wxk_customer")->column('external_user_id');
        $access_token = "LqfodA70Ke3o0VJoow9wkuOxCgKwRyYEpv8CZvzsCVuT_qFgGyIjymoNmqHY0Q79j_ZwHctUB2ekXsSHxzuRAsyGto2uCHB-j-Fe0zJ9fXtoGSE-ONi8K5cLh8P2Mu-eTIa9gnhs6fkhJnEDwX8NbKZXw1aeLcRUCx1UDPaNBUQ2dUcP8KAUte-mQ7d-GQRMohLFHZM5FzYritwYUXXNCA";
        //分200循环处理
        try {
            $chunkSize = 200;
            $totalUsers = count($user_ids);
            for ($i = 0; $i < $totalUsers; $i += $chunkSize) {
                $chunk = array_slice($user_ids, $i, $chunkSize);
                // 验证 access_token 和 user_ids 的合法性
                if (empty($access_token) || empty($chunk)) {
                    throw new \InvalidArgumentException("Invalid access_token or user_ids");
                }
                // 获取新的外部用户 ID
                $res = $wechat->get_new_external_userid($access_token, $chunk);
                // 检查返回数据格式
                if (!isset($res['items']) || !is_array($res['items'])) {
                    throw new \RuntimeException("Unexpected response format from get_new_external_userid");
                }
                // 插入数据库
                Db::name("userid_extend")->insertAll($res['items']);
            }
        } catch (\Exception $e) {
            Log::error("Error processing user IDs: " . $e->getMessage());
        }
        // 指令输出
        $output->writeln('hello');
    }
}
